//
//  MGSecondFloorRefreshHeader.m
//  MGTV-iPhone
//
//  Created by Qeye Wang on 2019/3/5.
//  Copyright © 2019 hunantv. All rights reserved.
//

#import "MGSecondFloorRefreshHeader.h"

/** 新增一个动作类型，为了解决在松手时contentOffset不好比较，不执行动作 */
typedef NS_ENUM(NSUInteger, SFAction) {
    SFAction_None,
    SFAction_Refresh,
    SFAction_SecondFloor,
};

@interface MGSecondFloorRefreshHeader ()
@property (assign, nonatomic) SFAction actionType;
@property (assign, nonatomic) BOOL trackedImpression;
@property (strong, nonatomic) NSString *refreshText;
@property (strong, nonatomic) NSString *refreshingText;
@property (strong, nonatomic) NSString *secondFloorText;
@property (assign, nonatomic) CGFloat insetTDelta;
@property (strong, nonatomic) NSLayoutConstraint *tipsLabelWidthConstraint;
@end

@implementation MGSecondFloorRefreshHeader

+ (instancetype)headerWithRefreshBlock:(MJRefreshComponentAction)refreshBlock {
    MGSecondFloorRefreshHeader *header = [[self alloc] init];
    header.refreshingBlock = refreshBlock;
    return header;
}

+ (instancetype)headerWithRefreshTarget:(id)target refreshAction:(SEL)action {
    MGSecondFloorRefreshHeader *header = [[self alloc] init];
    [header setRefreshingTarget:target refreshingAction:action];
    return header;
}

- (void)updateTipsLabel:(NSString *)tips {
    if (tips && [tips isEqualToString:self.tipsLabel.text]) {
        return;
    }
    self.tipsLabel.text = tips;
    
    NSDictionary *attribute = @{NSFontAttributeName:self.tipsLabel.font};
    CGSize outPutSize = [tips boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
    
    CGFloat width = ceilf(outPutSize.width) + 20;
    CGFloat screenWidth = MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    width = MIN(width, screenWidth - 20);
    if (!_tipsLabelWidthConstraint) {
        _tipsLabelWidthConstraint = [self.tipsLabel.widthAnchor constraintEqualToConstant:width];
        [_tipsLabelWidthConstraint setActive:YES];
    } else {
        _tipsLabelWidthConstraint.constant = width;
    }
}

- (void)enterSecondFloor {
    if (self.secondFloorBlock) {
        self.secondFloorBlock();
    }
    self.state = MJRefreshStateIdle;
    self.tipsLabel.alpha = 0;
}

- (void)notifAlphaChange:(CGFloat)alpha anime:(BOOL)anime {
    [[NSNotificationCenter defaultCenter] postNotificationName:MGSecondFloorRefreshHeaderAlphaNotif
                                                        object:self
                                                      userInfo:@{@"alpha": @(alpha), @"anime": @(anime),@"channelId": self.channelId?:@""}];
    if (_alphaChangeBlock) {
        _alphaChangeBlock(alpha, anime);
    }
    
}
#pragma mark - Properties

- (void)setSFView:(UIView<SecondFloorViewProcotol> *)SFView {
    if ([_SFView isEqual:SFView] && SFView.superview && SFView.superview == self) {
        return;
    }
    [_SFView removeFromSuperview];
    _SFView = SFView;
    if (SFView) {
        [SFView removeFromSuperview];
        SFView.frame = CGRectMake(0, self.mj_h-SFView.frame.size.height, self.frame.size.width, SFView.frame.size.height);
        CGFloat alpha = 0;
        if (self.refreshThreshold != 0) {//沿用上次的alpha值
            alpha = MIN(self.pullingPercent/self.refreshThreshold, 1.);
        }
        [self updateContentAlpha:alpha];
        [self insertSubview:SFView atIndex:0];
        self.trackedImpression = NO;
    }
}

- (UILabel *)tipsLabel {
    if (!_tipsLabel) {
        _tipsLabel = [UILabel new];
        _tipsLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightSemibold];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.textColor = [UIColor whiteColor];
        _tipsLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
        _tipsLabel.layer.masksToBounds = YES;
        _tipsLabel.layer.cornerRadius = 14;
    }
    return _tipsLabel;
}

#pragma mark - 重写父类的方法
- (void)prepare {
    [super prepare];
    // 设置高度
    self.mj_h = MAX([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    self.refreshThreshold = 0.15;
    self.secondFloorThreshold = 0.35;
    [self addSubview:self.tipsLabel];
    
    [[self.tipsLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor] setActive:YES];
    [[self.tipsLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-15] setActive:YES];
    [[self.tipsLabel.heightAnchor constraintEqualToConstant:28] setActive:YES];
    
    self.refreshText = @"刷新页面";
    self.refreshingText = @"刷新中";
    self.secondFloorText = @"继续下拉发现更多惊喜";
}

- (void)placeSubviews {
    [super placeSubviews];
    self.mj_y = -self.mj_h;
}

- (void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    if (!newSuperview) {
        _scrollView.contentInset = _scrollViewOriginalInset;
        [self notifAlphaChange:0 anime:NO];//二楼从有到无的时候 会导致头部展示异常 因为开始刷新的时候 把头部的alpha改成0 这里需要改回来
    }
}

- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change {
    [super scrollViewContentOffsetDidChange:change];
    
    // 在刷新的refreshing状态
    if (self.state == MJRefreshStateRefreshing) {
        CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top;
        // 刷新状态时继续往下滑需要显示头部
        if (insetT == 0) {
            [self notifAlphaChange:0 anime:NO];
            insetT = self.scrollView.mj_h+_scrollViewOriginalInset.top;
        } else {
            [self notifAlphaChange:1 anime:NO];
        }
        insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT;
        self.scrollView.mj_insetT = insetT;
        
        self.insetTDelta = _scrollViewOriginalInset.top - insetT;
        return;
    }
    if (self.state == MJRefreshStateWillIdle) {
        return;
    }
    // 跳转到下一个控制器时，contentInset可能会变
    _scrollViewOriginalInset = self.scrollView.contentInset;
    // 当前的contentOffset
    CGFloat offsetY = self.scrollView.mj_offsetY;
    // 头部控件刚好出现的offsetY
    CGFloat happenOffsetY = - self.scrollViewOriginalInset.top;
    // 如果是向上滚动到看不见头部控件，直接返回
    if (offsetY > happenOffsetY) {
        self.pullingPercent = 0.0;
        return;
    }
    // 普通 和 即将刷新 的临界点
    CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h;
    if (self.scrollView.isDragging) { // 如果正在拖拽
        self.triggerByManual = YES;
        
        //每次下拉都要曝光上报
        if (NO == self.trackedImpression) {
            self.trackedImpression = YES;
//            if ([self.SFView isKindOfClass:[MgMiRefreshAdView class]]) { // 广告二楼控件的曝光逻辑
//                [((MgMiRefreshAdView *)self.SFView) trackImpression];
//            }
        }
        
        self.pullingPercent = pullingPercent;
        if (pullingPercent >= self.refreshThreshold) {
            self.state = MJRefreshStatePulling;
        } else {
            self.state = MJRefreshStateIdle;
        }
    } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
//        MgMiRefreshAdView *adView;
//        if ([self.SFView isKindOfClass:[MgMiRefreshAdView class]]) {
//            adView = (MgMiRefreshAdView *)self.SFView;
//        }
//        if (adView && adView.infoModel.type == MGADDetailTypeNone) {
//            if (self.actionType == SFAction_Refresh) {
//                [self beginRefreshing];
//            }
//        } else
        if (self.actionType == SFAction_SecondFloor) {
            [self enterSecondFloor];
        } else if (self.actionType == SFAction_Refresh) {
            [self beginRefreshing];
        }
    } else {
        self.pullingPercent = pullingPercent;
    }
}

- (void)scrollViewPanStateDidChange:(NSDictionary *)change {
    [super scrollViewPanStateDidChange:change];
    // 在刷新的refreshing状态
    if (self.state == MJRefreshStateRefreshing) {
        CGPoint translatedPoint = [self.scrollView.panGestureRecognizer translationInView:self.scrollView];
        // 向上滑才处理
        if (translatedPoint.y > 0) {
            NSNumber *newValue = change[NSKeyValueChangeNewKey];
            // 手势取消的时候强制滚动到二楼的刷新状态
            if (newValue.integerValue == UIGestureRecognizerStateEnded || newValue.integerValue == UIGestureRecognizerStateCancelled) {
                [self.scrollView setContentOffset:CGPointMake(0, -self.scrollViewOriginalInset.top - 20) animated:YES];
            }
        }
    }
}

- (void)setState:(MJRefreshState)state {
    MJRefreshCheckState
    // 根据状态做事情
    if (state == MJRefreshStateWillIdle || state == MJRefreshStateIdle) {
        if (oldState != MJRefreshStateRefreshing) return;
        // 恢复inset和offset
        [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
            self.scrollView.mj_insetT += self.insetTDelta;
        } completion:^(BOOL finished) {
            self.pullingPercent = 0.0;
            [self notifAlphaChange:0 anime:YES];
            if (self.endRefreshingCompletionBlock) {
                self.endRefreshingCompletionBlock();
            }
            self.triggerByManual = NO;
            self.trackedImpression = NO;//动画结束
            self.state = MJRefreshStateIdle;
        }];
    } else if (state == MJRefreshStateRefreshing) {
        self.pullingPercent = self.refreshThreshold;
        [self updateTipsLabel:self.refreshingText];
        [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
            CGFloat top = self.scrollViewOriginalInset.top + self.mj_h*self.refreshThreshold;
            // 增加滚动区域top
            self.scrollView.mj_insetT = top;
            // 设置滚动位置
            [self.scrollView setContentOffset:CGPointMake(0, -top) animated:NO];
        } completion:^(BOOL finished) {
            [self executeRefreshingCallback];
        }];
    }
}

- (void)setPullingPercent:(CGFloat)pullingPercent {
    BOOL changed = pullingPercent != self.pullingPercent;
    if (!changed) {
        return;
    }
    [super setPullingPercent:pullingPercent];
    
    
    if ([self.SFView.superview isEqual:self]) {
        CGFloat alpha = MIN(pullingPercent/self.refreshThreshold, 1.);
        [self updateContentAlpha:alpha];
        [self notifAlphaChange:alpha anime:NO];
        
        if (alpha == 0  && self.triggerByManual) self.trackedImpression = NO;
        if (alpha == 1 && !self.moduleShowReport) {
            self.moduleShowReport = YES;
//            ModuleShowStatistics *showData = [[ModuleShowStatistics alloc] init];
//            NSString *flag = @"116";
//            // 不同的控件，可能上报的flag值不同
//            if ([self.SFView respondsToSelector:@selector(moduleShowFlag)]) {
//                flag = [self.SFView moduleShowFlag];
//            }
            BOOL hasAutoRefresh = [self.SFView respondsToSelector:@selector(isAutoReFresh)];
//            showData.flag = flag;
//            showData.lob = [NSString stringWithFormat:@"smod=1&cont=%@&stype=%@",self.SFView.pullingTips, hasAutoRefresh ? (self.SFView.isAutoReFresh ? @(0) : @(1)) : @(1)];
//            [ImgoStatisticsConn postModuleShowStatisticsReport:showData];
            if (hasAutoRefresh) {
                [self.SFView setIsAutoRefresh:NO];
            }
        }
    } else {
        [self notifAlphaChange:0 anime:YES];
    }
    
//    MgMiRefreshAdView *adView;
//    if ([self.SFView isKindOfClass:[MgMiRefreshAdView class]]) {
//        adView = (MgMiRefreshAdView *)self.SFView;
//    }
//    
//    if (adView && adView.infoModel.type == MGADDetailTypeNone) {
//        if (pullingPercent >= self.refreshThreshold) {
//            self.actionType = SFAction_Refresh;
//        } else {
//            self.actionType = SFAction_None;
//        }
//        [self updateTipsLabel:self.refreshText];
//    } else
    if (pullingPercent >= self.secondFloorThreshold) {
        self.actionType = SFAction_SecondFloor;
        NSString *moreTips;
        if (self.SFView && [self.SFView respondsToSelector:@selector(moreTips)]) {
            moreTips = [self.SFView moreTips];
        }
        [self updateTipsLabel:moreTips];
    } else if (pullingPercent >= self.refreshThreshold) {
        self.actionType = SFAction_Refresh;
        NSString *pullingTips = @"发现更多惊喜";
        if (self.SFView && [self.SFView respondsToSelector:@selector(pullingTips)]) {
            pullingTips = [self.SFView pullingTips];
        }
        [self updateTipsLabel:pullingTips];
    } else {
        self.actionType = SFAction_None;
        [self updateTipsLabel:self.secondFloorText];
    }
}

- (void)updateContentAlpha:(CGFloat)alpha{
    self.SFView.alpha = alpha;
    self.tipsLabel.alpha = alpha;
}

- (void)beginRefreshing {
    [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
        self.alpha = 1.0;
    }];
    
    // 只要正在刷新，就完全显示
    if (self.window) {
        self.state = MJRefreshStateRefreshing;
    } else {
        // 预防正在刷新中时，调用本方法使得header inset回置失败
        if (self.state != MJRefreshStateRefreshing) {
            self.state = MJRefreshStateWillRefresh;
            // 刷新(预防从另一个控制器回到这个控制器的情况，回来要重新刷新一下)
            [self setNeedsDisplay];
        }
    }
    //上报非手动触发的下拉曝光
    if (NO == self.triggerByManual && NO == self.trackedImpression) {
        self.trackedImpression = YES;
//        if ([self.SFView isKindOfClass:[MgMiRefreshAdView class]]) {
//            [((MgMiRefreshAdView *)self.SFView) trackImpression];
//        }
    }
}

- (void)setTrackedImpression:(BOOL)trackedImpression{
    _trackedImpression = trackedImpression;
    if(!_trackedImpression){//模块上报复原时机跟曝光复原时机一致
        _moduleShowReport = _trackedImpression;
    }
}

- (void)endRefreshing {
    if (self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh) {
        self.state = MJRefreshStateWillIdle;
    }
    //self.scrollView.mj_insetT = self.scrollViewOriginalInset.top;
}

@end
